package com.ask.controller;

import com.ask.dto.Result;
import com.ask.entity.Blog;
import com.ask.service.businessService.IBlogService;
import com.ask.service.businessService.IUserService;
import com.ask.threadlocals.UserHolder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.ask.constants.SystemConstants.MAX_PAGE_SIZE;

@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    private IBlogService blogService;

    @Autowired
    private IUserService userService;


    /**
     * 新增笔记
     *
     * @param blog
     * @return
     */
    @PostMapping
    public Result saveBlog(@RequestBody Blog blog) {
        return blogService.saveBlog(blog);
    }

    /**
     * 查询用户笔记
     *
     * @return
     */
    @GetMapping("/of/me")
    public Result queryBlog(@RequestParam(defaultValue = "1") Integer current) {
        Long userId = UserHolder.getUser().getId();
        Page<Blog> page = blogService.query().eq("user_id", userId)
                .page(new Page<>(current, MAX_PAGE_SIZE));
        List<Blog> records = page.getRecords();
        return Result.success(records);
    }

    /**
     * 根据id查询博客
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result queryBlogById(@PathVariable("id") Long id) {
        return blogService.queryBlogById(id);
    }

    /**
     * 查询热门博客
     *
     * @param current
     * @return
     */
    @GetMapping("/hot")
    public Result queryHotBlog(
            @RequestParam(value = "current", defaultValue = "1") Integer current) {
        return blogService.queryHotBlog(current);
    }

    /**
     * 博客点赞
     *
     * @param id
     * @return
     */
    @PutMapping("/like/{id}")
    public Result likeBlog(@PathVariable("id") Long id) {
        return blogService.likeBlog_V3(id);
    }

    /**
     * 查询博客的点赞排行
     *
     * @param id
     * @return
     */
    @GetMapping("/likes/{id}")
    public Result queryBlogLikes(@PathVariable("id") Long id) {
        return blogService.queryBlogLikes(id);
    }

    /**
     * 查询某个用户的博客
     *
     * @param userId
     * @param current
     * @return
     */
    @GetMapping("/of/user")
    public Result queryUserBlog(
            @RequestParam("id") Long userId,
            @RequestParam(value = "current", defaultValue = "1") Integer current) {
        Page<Blog> page = blogService
                .query()
                .eq("user_id", userId)
                .page(new Page<>(current, MAX_PAGE_SIZE));
        return Result.success(page.getRecords());
    }

    @GetMapping("/of/follow")
    public Result queryBlogOfFollow(
            @RequestParam(value = "lastId") Long max,
            @RequestParam(value = "offset", defaultValue = "0") Integer offset) {
        return blogService.queryBlogOfFollow(max,offset);
    }


}
